﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.Business.Prod;
using ESOL.Common;
using ESOL.Business.Sales;
using ESOL.WinUI.Hr;

namespace ESOL.WinUI.Manufacture
{
    public partial class frmManageReportWorking : BaseForm.frmBaseMdiChildForm
    {
        #region Variables
        private ProdPlanOrderItemEntity SelectedProdPlanOrderItem;
        #endregion

        #region ctors
        public frmManageReportWorking()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void SetField()
        {
            if (SelectedProdPlanOrderItem == null)
                return;
            txtOrderItem.Text = SelectedProdPlanOrderItem.OrderItemCode;
            txtOrderItem.Tag = SelectedProdPlanOrderItem;
            MstProductEntity mProduct = MstProductBs.GetMstProductTypeByID(SelectedProdPlanOrderItem.ProductId);
            txtStdName.Text = mProduct.StdName;
            txtSpecIn.Text = mProduct.ProductSpecIn;
            txtProductName.Text = mProduct.ProductName;
            txtProductCode.Text = mProduct.ProductCode;
            txtDescription.Text = mProduct.Description;
            txtPlanQty.Text = SelectedProdPlanOrderItem.Qty.ToString();
        }
        private void BindGridData()
        {
            if (SelectedProdPlanOrderItem == null)
                return;
            DataTable dt = ProdWorkingReportBs.GetDtWorkingReportByItemID(SelectedProdPlanOrderItem.PlanOrderItemId);
            gvDetail.DataSource = dt;
        }
        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtStation.Text))
            {
                MessageBox.Show("工序不可为空!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtStation.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtQty.Text))
            {
                MessageBox.Show("报工数量错误!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtQty.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtPerson.Text))
            {
                MessageBox.Show("加工人不可为空!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtPerson.Focus();
                return false;
            }
            return true;
        }

        private bool CheckReport()
        {
            if (SelectedProdPlanOrderItem == null)
            {
                MessageBox.Show("工令单不能为空！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            //当前工令单工序序号
            List<ProdProductTechnicEntity> list = ProdProductTechnicBs.GetProdProductTechnicByItemID(SelectedProdPlanOrderItem.PlanOrderItemId);
            int nIndex = -1;
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].ProductTechnicId.Equals(((ProdProductTechnicEntity)txtStation.Tag).ProductTechnicId))
                {
                    nIndex = i;
                    break;
                }
            }
            //当前工序的已报工数量
            DataTable dt1 = ProdWorkingReportBs.GetDtReportTotalQtyByProductTechnicID(((ProdProductTechnicEntity)txtStation.Tag).ProductTechnicId);
            decimal nCurStationReportedQty = 0;
            if (!string.IsNullOrEmpty(dt1.Rows[0]["REPORTED_TOTAL_QTY"].ToString()))
                nCurStationReportedQty = Convert.ToDecimal(dt1.Rows[0]["REPORTED_TOTAL_QTY"].ToString());
            //重工工单
            if (SelectedProdPlanOrderItem.OrderType.Equals("POIT02"))
            {
                //判断是否首站，是则原工令单的已报数量
                if (nIndex == 0)
                {
                    ProdPlanOrderItemEntity mRelatedPlanOrderItem = ProdPlanOrderItemBs.GetProdPlanOrderItemByID(SelectedProdPlanOrderItem.RelatedPlanOrderItemId);
                    if (mRelatedPlanOrderItem == null)
                    {
                        MessageBox.Show("原工令单不存在，报工失败！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                    DataTable dtReportedQty = ProdWorkingReportBs.GetDtMaxReportedQtyByPlanOrderItemID(mRelatedPlanOrderItem.PlanOrderItemId);
                    if (string.IsNullOrEmpty(dtReportedQty.Rows[0][0].ToString()) == false)
                    {
                        //原工令单已报工最大数量
                        decimal ReportedTotalQty = Convert.ToDecimal(dtReportedQty.Rows[0][0].ToString());
                        if (Convert.ToDecimal(txtQty.Text) + nCurStationReportedQty > ReportedTotalQty)
                        {
                            MessageBox.Show("超过原工令单已报工数量！", "Inforamtion", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        else if (nCurStationReportedQty + Convert.ToDecimal(txtQty.Text) > SelectedProdPlanOrderItem.Qty)
                        {
                            MessageBox.Show("超过该工令单需求数量！", "Inforamtion", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                    }
                    return true;

                }
            }
            //判断工令单状态：下料中、生产中
            if (SelectedProdPlanOrderItem.Status.Equals("POI04") == false
                && SelectedProdPlanOrderItem.Status.Equals("POI05") == false
                && SelectedProdPlanOrderItem.Status.Equals("POI06") == false)
            {
                MessageBox.Show("工令单状态不正确！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (nIndex != 0)
            {
                DataTable dt = ProdWorkingReportBs.GetDtReportTotalQtyByProductTechnicID(list[nIndex - 1].ProductTechnicId);
                if (string.IsNullOrEmpty(dt.Rows[0]["REPORTED_TOTAL_QTY"].ToString()))
                {
                    MessageBox.Show("上一道工序尚未报工！", "Inforamtion", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
                else if (Convert.ToDecimal(dt.Rows[0]["REPORTED_TOTAL_QTY"].ToString()) <
                    Convert.ToDecimal(txtQty.Text) + nCurStationReportedQty)
                {
                    MessageBox.Show("超过上道工序已报工数量！", "Inforamtion", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
                else if (nCurStationReportedQty + Convert.ToDecimal(txtQty.Text) > SelectedProdPlanOrderItem.Qty)
                {
                    MessageBox.Show("超过该工令单需求数量！", "Inforamtion", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
            }
            else//第一站
            {
                if ((nCurStationReportedQty + Convert.ToDecimal(txtQty.Text)) > SelectedProdPlanOrderItem.Qty)
                {
                    MessageBox.Show("超过该工令单需求数量！", "Inforamtion", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
            }
            //}
            return true;
        }

        private bool Save()
        {
            ProdWorkingReportEntity mProdWorkingReport = new ProdWorkingReportEntity();
            mProdWorkingReport.ReportId = Guid.NewGuid().ToString();
            mProdWorkingReport.ProductTechnicId = ((ProdProductTechnicEntity)txtStation.Tag).ProductTechnicId;
            mProdWorkingReport.ReportPerson = ((MstPersonEntity)txtPerson.Tag).PersonId;
            mProdWorkingReport.ReportDate = DateTime.Today;
            mProdWorkingReport.ReportQty = CommonFunctions.ToDecimal(txtQty.Text);
            mProdWorkingReport.CreateDate = DateTime.Today;
            mProdWorkingReport.CreateBy = CommonParameter.CurrentUser.PersonId;
            mProdWorkingReport.Remark = txtRemark.Text;
            mProdWorkingReport.Status = NormalStatus.STATUS02.ToString();
            mProdWorkingReport.FinishDate = DateTime.Today;
            if (ProdWorkingReportBs.CreateReportOrder(mProdWorkingReport, SelectedProdPlanOrderItem.PlanOrderItemId))
                return true;
            else return false;
        }

        private void SendMessageToSales(string sMessageTitle, string sSender, string sMessageBody, string MessageLevel, List<MstPersonEntity> listTo)
        {
            MstMessageEntity message = new MstMessageEntity();
            message.MessageId = Guid.NewGuid().ToString();
            message.MessateTitle = sMessageTitle;
            message.MessageSender = sSender;
            message.MessageBody = sMessageBody;
            message.MessageLevel = MessageLevel;
            message.FormName = "ESOL.WinUI.Sales.FrmSalesOverview";
            message.MessageDate = DateTime.Now;//btnModify
            MstMessageBs.SendMessage(message, listTo);
        }

        #endregion

        #region Events
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            SetField();
            BindGridData();
            txtOrderItem.Focus();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            BindGridData();
        }

        private void btnReport_Click(object sender, EventArgs e)
        {
            if (CheckData() && CheckReport())
            {
                ProdProductTechnicEntity m = (ProdProductTechnicEntity)txtStation.Tag;
                if (Save())
                {
                    BindGridData();
                    MessageBox.Show("报工成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DataTable dt = ProdProductTechnicBs.GetDtItemFlowStationByItemID(SelectedProdPlanOrderItem.PlanOrderItemId);
                    DataRow[] arryDataRow = dt.Select("PRODUCT_TECHNIC_ID='" + m.ProductTechnicId + "'");
                    int nIndex = dt.Rows.IndexOf(arryDataRow[0]);
                    if (dt.Rows.Count - 1 > nIndex)
                    {
                        if (dt.Rows[nIndex + 1]["STATION_TYPE"].ToString().Equals("STT06"))//当前报工工序下一站是外协站
                        {
                            frmMaintainCooperation frm = new frmMaintainCooperation(m);
                            frm.ThisActionType = ActionType.New;
                            frm.ShowDialog();
                        }
                    }
                    ProdPlanOrderEntity mPlanOrder = ProdPlanOrderBs.GetProdPlanOrderByID(SelectedProdPlanOrderItem.PlanOrderId);
                    if (mPlanOrder != null)
                    {
                        if (mPlanOrder.Status.Equals("PSTATUS07"))
                        {
                            SalesProdPlanApplicationItemEntity mProdPlanApplicationItem = SalesProdPlanApplicationItemBs.GetProdPlanApplicationItemByID(mPlanOrder.ApplicationItemId);
                            if (mProdPlanApplicationItem == null)
                                return;
                            SalesProdPlanApplicationEntity mProdPlanApplication = SalesProdPlanApplicationBs.GetSalesProdPlanApplicationByID(mProdPlanApplicationItem.ApplicationId);
                            if (mProdPlanApplication == null)
                                return;
                            MstPersonEntity mPerson = MstPersonBs.GetMstPersonByID(mProdPlanApplication.CreatedBy);
                            List<MstPersonEntity> listPerson = new List<MstPersonEntity>();
                            listPerson.Add(mPerson);
                            SendMessageToSales("发货通知", Common.CommonParameter.CurrentUser.PersonId, "生产单：" + mPlanOrder.PlanOrderCode + " 已完成！", MessageLevel.ML03.ToString(), listPerson);
                        }
                    }
                    return;
                }
            }
            txtOrderItem.SelectAll();
            txtOrderItem.Focus();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }

        private void txtOrderItem_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)
            {
                return;
            }
            if (string.IsNullOrEmpty(txtOrderItem.Text) == true)
            {
                return;
            }
            SelectedProdPlanOrderItem = ProdPlanOrderItemBs.GetProdPlanOrderItemByCode(txtOrderItem.Text);
            if (SelectedProdPlanOrderItem == null)
            {
                MessageBox.Show("工令单不存在！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            txtOrderItem.Tag = SelectedProdPlanOrderItem;
            SetField();
            BindGridData();
        }
        private void txtStation_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainWorkingOrderTechnicQuery frm = new frmMaintainWorkingOrderTechnicQuery(SelectedProdPlanOrderItem);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProdProductTechnic != null)
            {
                ProdTechnicEntity m = ProdTechnicBs.GetProdTechnicByProductTechnicID(frm.SelectedProdProductTechnic.ProductTechnicId);
                if (m != null)
                {
                    txtStation.Text = m.TechnicName;
                    txtStation.Tag = frm.SelectedProdProductTechnic;

                    DataTable dt = ProdWorkingReportBs.GetDtReportTotalQtyByProductTechnicID(frm.SelectedProdProductTechnic.ProductTechnicId);
                    if (dt != null && dt.Rows.Count > 0 && !string.IsNullOrEmpty(dt.Rows[0][0].ToString()))
                        txtReportedQty.Text = dt.Rows[0]["REPORTED_TOTAL_QTY"].ToString();
                    else txtReportedQty.Text = "0";
                }
            }
        }
        private void txtPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery(true);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtPerson.Text = frm.SelectedPerson.NameCn;
                txtPerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtPerson.Text = "";
                txtPerson.Tag = null;
            }
        }
        private void txtOrderItem_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainWorkingOrderQuery frm = new frmMaintainWorkingOrderQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProdPlanOrderItem != null)
            {
                txtOrderItem.Text = frm.SelectedProdPlanOrderItem.OrderItemCode;
                txtOrderItem.Tag = frm.SelectedProdPlanOrderItem;
                SelectedProdPlanOrderItem = frm.SelectedProdPlanOrderItem;
            }
            else
            {
                txtOrderItem.Text = "";
                txtOrderItem.Tag = null;
                SelectedProdPlanOrderItem = null;
            }
            SetField();
            BindGridData();
        }
        #endregion
    }
}
